package com.waigoulin.infrastructure.adapter.repository;

import com.google.common.eventbus.EventBus;
import com.waigoulin.domain.order.adapter.event.PaySuccessMessageEvent;
import com.waigoulin.domain.order.adapter.repository.IOrderDaoRepository;
import com.waigoulin.domain.order.model.aggregate.CreateOrderAggregate;
import com.waigoulin.domain.order.model.entity.OrderEntity;
import com.waigoulin.domain.order.model.entity.PayOrderEntity;
import com.waigoulin.domain.order.model.entity.ProductEntity;
import com.waigoulin.domain.order.model.entity.ShopCartEntity;
import com.waigoulin.domain.order.model.valobj.OrderStatusVO;
import com.waigoulin.infrastructure.dao.IOrderDao;
import com.waigoulin.infrastructure.dao.po.PayOrder;
import com.waigoulin.types.event.BaseEvent;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @FileName OrderRepository
 * @Description 订单基础设施（仓储/持久化）层接口实现类
 * @Author waigoulin
 * @date 2025-07-31
 **/
@Repository
public class OrderRepository implements IOrderDaoRepository {

    @Resource
    private IOrderDao orderDao;

    @Resource
    private EventBus eventBus;

    @Resource
    private PaySuccessMessageEvent paySuccessMessageEvent;

    @Override
    public void doSaveOrder(CreateOrderAggregate createOrderAggregate) {
        // 1. 获取订单商品聚合对象内的订单和商品实体对象
        OrderEntity orderEntity = createOrderAggregate.getOrderEntity();
        ProductEntity productEntity = createOrderAggregate.getProductEntity();

        // 2. 调用dao包查询
        orderDao.insert(PayOrder.builder()
                .userId(createOrderAggregate.getUserId())
                .orderId(orderEntity.getOrderId())
                .productId(productEntity.getProductId())
                .productName(productEntity.getProductName())
                .orderTime(LocalDateTime.now())
                .totalAmount(productEntity.getPrice())
                .status(OrderStatusVO.CREATE.getCode()) // 创建的流水单默认是CREATE状态，成功创建支付单后才会调用方法修改为PAY_WAIT状态
                .build()
        );
    }

    @Override
    public OrderEntity queryUnPayOrder(ShopCartEntity shopCartEntity) {
        // 1. 封装查询参数
        PayOrder payOrderReq = PayOrder.builder()
                .userId(shopCartEntity.getUserId())
                .productId(shopCartEntity.getProductId())
                .build();
        // 2. 查询未支付的订单
        PayOrder payOrder = orderDao.queryUnPayOrder(payOrderReq);

        if (payOrder == null) {
            return null;
        }

        return OrderEntity.builder()
                .id(payOrder.getId())
                .userId(payOrder.getUserId())
                .productId(payOrder.getProductId())
                .productName(payOrder.getProductName())
                .orderId(payOrder.getOrderId())
                .orderTime(payOrder.getOrderTime())
                .totalAmount(payOrder.getTotalAmount())
                .orderStatusVO(OrderStatusVO.valueOf(payOrder.getStatus()))
                .payUrl(payOrder.getPayUrl())
                .build();
    }

    @Override
    public void updateOrderPayInfo(PayOrderEntity payOrderEntity) {
        PayOrder payOrderReq = PayOrder.builder()
                .userId(payOrderEntity.getUserId())
                .orderId(payOrderEntity.getOrderId())
                .payUrl(payOrderEntity.getPayUrl())
                .status(payOrderEntity.getOrderStatus().getCode())
                .build();
        orderDao.updateOrderPayInfo(payOrderReq);
    }

    @Override
    public void changeOrderPaySuccess(String orderId) {
        // 1. 封装修改参数
        PayOrder payOrderReq = PayOrder.builder()
                .orderId(orderId)
                .status(OrderStatusVO.PAY_SUCCESS.getCode())
                .build();
        // 2. 调用dao包进行修改
        orderDao.changeOrderPaySuccess(payOrderReq);

        // 通过消息总线发送消息
        BaseEvent.EventMessage<PaySuccessMessageEvent.PaySuccessMessage> paySuccessMessageEventMessage = paySuccessMessageEvent.buildEventMessage(
                PaySuccessMessageEvent.PaySuccessMessage.builder()
                        .userId(payOrderReq.getUserId())
                        .tradeNo(orderId)
                        .build());
        PaySuccessMessageEvent.PaySuccessMessage data = paySuccessMessageEventMessage.getData();
        eventBus.post(paySuccessMessageEventMessage);
    }

    @Override
    public List<String> queryNoPayNotifyOrder() {
        // 调用dao包进行查询
        return orderDao.queryNoPayNotifyOrder();
    }

    @Override
    public List<String> queryTimeoutCloseOrderList() {
        // 调用dao包进行查询
        return orderDao.queryTimeoutCloseOrderList();
    }

    @Override
    public boolean changeOrderClose(String orderId) {
        // 调用dao包进行修改
        return orderDao.changeOrderClose(orderId);
    }
}


